//基于原生Cesium的查询
function query(type) {
    switch (type) {
        case "spatial":
            spatialQueryFor3DMap(); //空间查询
            break;
        case "attribute":
            attributeQueryFor3DMap(); //属性查询
            break;
        case "dynamicMonomer":
            dynamicMonomerFor3DMap(); //单体化
            break;
    }
}

function getLayerInfoByName(layerName) {
    var obj = {};
    for (var i in m_MapConfigLayers["maplayers"]) {
        if (m_MapConfigLayers["maplayers"][i].name === layerName) {
            obj = {
                url: m_MapConfigLayers["maplayers"][i].layerurl,
                serverName: m_MapConfigLayers["maplayers"][i].layerid
            }
            break;
        }
    }
    return obj;
}

var layerId = "";
function spatialQueryFor3DMap() {
    var identifyQueryHandler;
    var position = null;
    RemoveAllLayers();
    changeContainerVisible('spatialQueryDiv');
    $(".select_attribute_selectLayer").empty();
    for (var attr in cesium.layer3DList) {
        var layerInfo = cesium.layer3DList[attr];
        if (layerInfo["SERVICETYPE"] == sw_servicetype.sw_tile || layerInfo["SERVICETYPE"] == sw_servicetype.sw_vector) {
            $(".select_attribute_selectLayer").append("<option value='" + attr + "'>" + layerInfo.NAME + "</option>");
        }
    }
    form.render('select');
    form.on('select(select_attribute_selectLayer)', function (data) {
        layerId = data.value;
    });

    //viewer.scene.globe.depthTestAgainstTerrain = false;
    layerId = $("#select_attribute_selectLayer option:selected").val();
    $("#queryPoint").unbind("click");
    $("#queryPoint").click(function () {
        position = null
        // identifyQuery(1);
        RemoveAllLayers();
        if (!layerId) { return showMsgLayer("请先开启或选择图层！"); }
        if (identifyQueryHandler) {
            identifyQueryHandler.destroy();
        }
        var tooltip = new GlobeTooltip(viewer.container);
        var cartesian = null;
        identifyQueryHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        var ellipsoid = viewer.scene.globe.ellipsoid;
        identifyQueryHandler.setInputAction(function(movement) {
            //通过指定的椭球或者地图对应的坐标系，将鼠标的二维坐标转换为对应椭球体三维坐标
            position = getPickPositionGlobe(movement.position);
            var bufferRadius = $("#bufferRadius").val();
            var value = position;
            if (bufferRadius === "" || bufferRadius === "0") {
                var pointArr = [];
                pointArr.push(value);
                var point84 = [mapProjectionToWGS84(pointArr)[0].longitude, mapProjectionToWGS84(pointArr)[0].latitude];
                queryLayerInfoByPoint(point84[0] + "," + point84[1], 1, [layerId]);
            } else if (bufferRadius > 0) {
                var center = Cartesian3_to_WGS84(value);
                var radius = parseFloat(bufferRadius);
                var options = { steps: 10, units: 'meters', properties: { foo: 'bar' } };
                var circle = turf.circle(center, radius, options);
                var coordinates = circle.geometry.coordinates[0];
                queryLayerInfoByPoint(pointArrsToStringForQuery(coordinates), 3, [layerId]);
                viewer.entities.add({
                    name: 'ellipse',
                    position: Cesium.Cartesian3.fromDegrees(center[0], center[1], 0),
                    ellipse: {
                        semiMajorAxis: 1 * radius, // 长轴长度
                        semiMinorAxis: 1 * radius, // 短轴长度
                        material: Cesium.Color.RED.withAlpha(0.3)
                    }
                });
            } else {
                showMsgLayer("请输入正确数值");
                return;
            }
            tooltip.setVisible(false);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    
        //鼠标移动
        identifyQueryHandler.setInputAction(function(event) {
            var wp = event.endPosition;
            if (!Cesium.defined(wp)) {
                return;
            }
            if (position == null) {
                tooltip.showAt(wp, "<p>单击选择位置</p>");
            }
            var cesium = getPickPositionGlobe(wp);
            if (!Cesium.defined(cesium)) {
                return;
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        
    });

    $("#queryLine").unbind("click");
    $("#queryLine").click(function () {
        if (!layerId) { return showMsgLayer("请先开启或选择图层！"); }
        removeAllEntities();
        tracker.trackPolyline(function(positions) {
            var bufferRadius = $("#bufferRadius").val();
            var value = positions;
            var points84 = mapProjectionToWGS84(value);
            var pointsArr = [];
            if (bufferRadius === "" || bufferRadius === "0") {
                for (var i = 0; i < points84.length; i++) {
                    pointsArr.push([points84[i].longitude, points84[i].latitude]);
                }
                var points = pointArrsToStringForQuery(pointsArr);
                queryLayerInfoByPoint(points, 4, [layerId]);
            } else if (bufferRadius > 0) {
                for (var i = 0; i < points84.length; i++) {
                    pointsArr.push([points84[i].longitude, points84[i].latitude]);
                }
                var line = turf.lineString(pointsArr);
                var buffered = turf.buffer(line, parseFloat(bufferRadius), { units: 'meters' });
                var point2 = (buffered.geometry.coordinates[0]);
                var point3 = [];
                for (var i = 0; i < point2.length; i++) {
                    point3.push(point2[i][0]);
                    point3.push(point2[i][1]);
                }
                queryLayerInfoByPoint(pointArrsToStringForQuery(point2), 3, [layerId]);
                viewer.entities.add({
                    name: 'polygon',
                    polygon: {
                        hierarchy: Cesium.Cartesian3.fromDegreesArray(point3),
                        material: Cesium.Color.RED.withAlpha(0.5),
                    }
                });
            } else {
                showMsgLayer("请输入正确数值");
                return;
            }
        });
    });

    $("#queryPolygon").unbind("click");
    $("#queryPolygon").click(function () {
        if (!layerId) { return showMsgLayer("请先开启或选择图层！"); }
        removeAllEntities();
        tracker.trackPolygon(function(positions) {
            var bufferRadius = $("#bufferRadius").val();
            var value = positions;
            value.push(value[0]);
            var points84 = mapProjectionToWGS84(value);
            var pointsArr = [];
            if (bufferRadius === "" || bufferRadius === "0") {
                for (var i = 0; i < points84.length; i++) {
                    pointsArr.push([points84[i].longitude, points84[i].latitude]);
                }
                queryLayerInfoByPoint(pointArrsToStringForQuery(pointsArr), 3, [layerId]);
            } else if (bufferRadius > 0) {
                for (var i = 0; i < points84.length; i++) {
                    pointsArr.push([points84[i].longitude, points84[i].latitude]);
                }
                pointsArr.push([points84[0].longitude, points84[0].latitude]);
                var polygon = turf.polygon([pointsArr]);
                var buffered = turf.buffer(polygon, parseFloat(bufferRadius), { units: 'meters' });
                var point2 = (buffered.geometry.coordinates[0]);
                var point3 = [];
                for (var i = 0; i < point2.length; i++) {
                    point3.push(point2[i][0]);
                    point3.push(point2[i][1]);
                }
                queryLayerInfoByPoint(pointArrsToStringForQuery(point2), 3, [layerId]);
                viewer.entities.add({
                    name: 'polygon',
                    polygon: {
                        hierarchy: Cesium.Cartesian3.fromDegreesArray(point3),
                        material: Cesium.Color.RED.withAlpha(0.5),
                    }
                });
            } else {
                showMsgLayer("请输入正确数值");
                return;
            }
        });
    });

    $("#queryRectangle").unbind("click");
    $("#queryRectangle").click(function (evt) {
        // rectangleIdentifyQuery();
        if (!layerId) { return showMsgLayer("请先开启或选择图层！"); }
        removeAllEntities();
        tracker.trackRectangle(function(positions) {
            var bufferRadius = $("#bufferRadius").val();
            var value = positions;
            var points84 = mapProjectionToWGS84(value);
            var pointsArr = [];
            pointsArr.push([points84[0].longitude, points84[0].latitude]);
            pointsArr.push([points84[0].longitude, points84[1].latitude]);
            pointsArr.push([points84[1].longitude, points84[1].latitude]);
            pointsArr.push([points84[1].longitude, points84[0].latitude]);
            pointsArr.push([points84[0].longitude, points84[0].latitude]);
            if (bufferRadius === "" || bufferRadius === "0") {
                queryLayerInfoByPoint(pointArrsToStringForQuery(pointsArr), 3, [layerId]);
            } else if (bufferRadius > 0) {
                var polygon = turf.polygon([pointsArr]);
                var buffered = turf.buffer(polygon, parseFloat(bufferRadius), { units: 'meters' });
                var point2 = (buffered.geometry.coordinates[0]);
                var point3 = [];
                for (var i = 0; i < point2.length; i++) {
                    point3.push(point2[i][0]);
                    point3.push(point2[i][1]);
                }
                queryLayerInfoByPoint(pointArrsToStringForQuery(point2), 3, [layerId]);
                viewer.entities.add({
                    name: 'polygon',
                    polygon: {
                        hierarchy: Cesium.Cartesian3.fromDegreesArray(point3),
                        material: Cesium.Color.RED.withAlpha(0.5),
                    }
                });
            } else {
                return showMsgLayer("请输入正确数值");
            }
        });
    });
}

function attributeQueryButtonHandle() {
    var layerId = $("#select_attributeQuery_selectLayer option:selected").val();
    if (!layerId) { return showMsgLayer("请先开启或选择图层！"); }
    if (($("#ipt_attributeQuery_value").val() === undefined || $("#ipt_attributeQuery_value").val() === "") && $("#select_attributeQuery_selectField").val() != 'all') {
        return showMsgLayer("请输入值后再查询");
    }
    var layerName = $("#select_attributeQuery_selectLayer").val();
    var fieldName = $("#select_attributeQuery_selectField").val();
    var fieldValue = $("#ipt_attributeQuery_value").val();
    var operation = $("#select_attribute_selectOperate").val();
    var layerItem = cesium.layer3DList[layerId];
    var layerUrl = layerItem["URL"];
    var result = null;
    var results = [];
    var isQueryAll = true;
    switch (layerItem["SERVICETYPE"]) {
        case sw_servicetype.sw_tile://tile
            switch (layerItem["SOURCE"]) {
                case sw_source.sw_arcgis://arcgis
                case sw_source.sw_arcgistile://arcgis
                    var params = {};
                    if (fieldName == "all") {//全选
                        queryUrl = layerUrl + "/0/query?where=1=1&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&having=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentOnly=false&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&f=json"
                    } else if (fieldValue.indexOf(",") > -1 || fieldValue.indexOf("，") > -1) {//多条件判断
                        if(fieldValue.indexOf(",") > -1){
                            var queryParams = fieldValue.split(",");
                        }else{
                            var queryParams = fieldValue.split("，");
                        }
                        var where = '(';
                        if (operation == "contains") {
                            for (var l = 0 ; l < queryParams.length ; l++) {
                                if (queryParams[l] == '') continue;
                                if (l > 0) {
                                    where += " or "
                                }
                                where += " " + fieldName + " like '%25" + queryParams[l] + "%25'";
                            }
                        } else if (operation == "equals") {
                            where += fieldName + " in (";
                            for (var l = 0 ; l < queryParams.length ; l++) {
                                if (queryParams[l] == '') continue;
                                if (l > 0) {
                                    where += ","
                                }
                                where += "'" + queryParams[l] + "'";
                            }
                            where += ")";
                        }
                        where += ")";
                        queryUrl = layerUrl + "/0/query?where=" + encodeURIComponent(where) + "&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&having=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentOnly=false&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&f=json"
                    } else {
                        queryUrl = layerUrl + '/find';
                        params = {
                            searchText: fieldValue,
                            contains: operation == "contains",
                            searchFields: fieldName,
                            layers: 'all',
                            f: 'json',
                            returnGeometry: true,
                            returnZ: false,
                            returnM: false,
                            sr: 4326
                        }
                        isQueryAll = false;
                    }
                    
                    $.get(queryUrl, params, function (data, status) {
                        if(data!=""){
                            if(typeof(data) === "string"){
                                data = JSON.parse(data)
                            }
                        }
                        result = handleToGeojson(data.results ? data.results : data.features, "arcgis");
                    });
                    break;
                case sw_source.sw_wms:
                    var filter = "";
                    var filterType = "";
                    switch (operation) {
                        case "contains":
                            filterType = "PropertyIsLike";
                            break;
                        case "equals":
                            filterType = "PropertyIsEqualTo";
                            break;
                        case "不等于":
                            filterType = "PropertyIsNotEqualTo";
                            break;
                        case "大于":
                            filterType = "PropertyIsGreaterThan";
                            break;
                        case "大于等于":
                            filterType = "PropertyIsGreaterThanOrEqualTo";
                            break;
                        case "小于":
                            filterType = "PropertyIsLessThan";
                            break;
                        case "小于等于":
                            filterType = "PropertyIsLessThanOrEqualTo";
                            break;
                    }
                    if (filterType === "PropertyIsLike")
                        filter = "<Filter xmlns='http://www.opengis.net/ogc' xmlns:gml='http://www.opengis.net/gml'><" + filterType + " wildCard='*' singleChar='.' escape='!'><PropertyName>" + fieldName + "</PropertyName><Literal>*" + fieldValue + "*</Literal></" + filterType + "></Filter>";
                    else
                        filter = "<Filter xmlns='http://www.opengis.net/ogc' xmlns:gml='http://www.opengis.net/gml'><" + filterType + " wildCard='*' singleChar='.' escape='!'><PropertyName>" + fieldName + "</PropertyName><Literal>" + fieldValue + "</Literal></" + filterType + "></Filter>";
                    var queryUrl = url + "?service=WFS&version=1.0.0&request=GetFeature&typeName=" + serverName + "&outputFormat=application/json&srsName=EPSG:4326&filter=" + filter;
                    $.getJSON(queryUrl, function (data) {
                        changeFeaturesForTable(data);
                    });
                    break;
                default:
                    break;
            }
            break;
        case sw_servicetype.vector://vector

            break;
        default:
            break;
    }
    if (result && result.features.length > 0) {
        results.push({
            name: layerItem["NAME"],
            id: layerId,
            data: result
        });
    }
    changeFeaturesForMap3DTable(results,isQueryAll);
}

function attributeQueryFor3DMap() {
    form.on('select(select_attributeQuery_selectLayer)', function (data) {
        getLayerFields();
    });
    RemoveAllLayers();
    changeContainerVisible('attributeQueryDiv');
    $("#select_attributeQuery_selectLayer").empty();
    for (var attr in cesium.layer3DList) {
        var layerInfo = cesium.layer3DList[attr];
        if (layerInfo["SERVICETYPE"] == sw_servicetype.sw_tile || layerInfo["SERVICETYPE"] == sw_servicetype.sw_vector) {
            $("#select_attributeQuery_selectLayer").append("<option value='" + attr + "'>" + layerInfo.NAME + "</option>");
        }
    }
    form.render('select');
    getLayerFields();
}

function getLayerFields() {
    $.ajaxSettings.async = false;
    var layerId = $("#select_attributeQuery_selectLayer option:selected").val();
    if (!layerId) { return }
    var layerItem = cesium.layer3DList[layerId];
    var queryUrl = "";
    var params = {};
    $("#select_attributeQuery_selectField").empty();
    var layerUrl = layerItem["URL"];
    switch (layerItem["SERVICETYPE"]) {
        case sw_servicetype.sw_tile://tile
            switch (layerItem["SOURCE"]) {
                case sw_source.sw_arcgis://arcgis
                case sw_source.sw_arcgistile://arcgis
                    queryUrl = layerUrl + '?f=json';
                    $.get(queryUrl, params, function (data, status) {
                        if(typeof(data) === "string"){
                            data = JSON.parse(data)
                        }
                        var layerFields = {};
                        for (var i = 0 ; i < data.layers.length ; i++) {
                            queryUrl = layerUrl + '/' + i + "?f=json";
                            $.get(queryUrl, params, function (data, status) {
                                if(typeof(data) === "string"){
                                    data = JSON.parse(data)
                                }
                                for (var k = 0 ; k < data.fields.length ; k++) {
                                    if (!layerFields[data.fields[k].name]) {
                                        layerFields[data.fields[k].name] = data.fields[k].alias;
                                    }
                                }
                            });
                        }
                        $("#select_attributeQuery_selectField").append("<option value='all'>全部</option>");
                        for (var attr in layerFields) {
                            if (attr.toLowerCase().indexOf("shape") > -1 || attr.toLowerCase().indexOf("object") > -1) { continue;}
                            if (LayerProperties[attr]) {
                                $("#select_attributeQuery_selectField").append("<option value=" + attr + ">" + LayerProperties[attr] + "</option>");
                            } else {
                                $("#select_attributeQuery_selectField").append("<option value=" + attr + ">" + layerFields[attr] + "</option>");
                            }
                        }
                    });
                    break;
                case sw_source.sw_wms:
                    var url = m_MapConfigLayers["maplayers"][i].layerurl + "?service=WFS&version=1.0.0&request=GetFeature&typeName=" + m_MapConfigLayers["maplayers"][i].layerid + "&maxFeatures=1&outputFormat=application%2Fjson";
                    $.getJSON(url, function (data) {
                        var obj = data.features[0].properties;
                        for (var i in obj) {
                            if (LayerProperties[i]) {
                                $("#select_attributeQuery_selectField").append("<option value=" + i + ">" + LayerProperties[i] + "</option>");
                            }
                        }
                    });
                    break;
                default:
                    break;
            }
            break;
        case sw_servicetype.vector://vector

            break;
        default:
            break;
    }
    form.render('select');
}

var dynamicMonomerHandler = null;

function dynamicMonomerFor3DMap() {
    RemoveAllLayers();
    changeContainerVisible();
    if ($("#dynamicMonomerQueryDiv").children().length === 0)
        createDynamicMonomerToolbar();
    $("#dynamicMonomerQueryDiv").children(".content").css("min-height", "60px");
    //$("#dynamicMonomerQueryDiv").show();
    $(".select_attribute_selectLayer").empty();
    var scene = viewer.scene;
    var camera = scene.camera;
    if (dynamicMonomerHandler) {
        dynamicMonomerHandler.destroy();
        dynamicMonomerHandler = null;
    }
    dynamicMonomerHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
    //鼠标左键
    dynamicMonomerHandler.setInputAction(function(event) {
        // 首先移除之前添加标识实体
        viewer.entities.removeById('identify-area');
        //var earthPosition = viewer.scene.camera.pickEllipsoid(event.position,  viewer.scene.globe.ellipsoid)
        // `earthPosition` will be undefined if our mouse is not over the globe.
        var earthPosition = getPickPositionGlobe(event.position);
        //highLightGltf(pick);//add by zhaowanfeng
        if (Cesium.defined(earthPosition)) {
            var queryUrl = "";
            var pointArr = [];
            pointArr.push(earthPosition);
            var point84 = [mapProjectionToWGS84(pointArr)[0].longitude, mapProjectionToWGS84(pointArr)[0].latitude, mapProjectionToWGS84(pointArr)[0].height];
            var pointArr2 = [];
            pointArr2.push(point84);
            var point = WGS84To2000(pointArr2, true);
            //var url = "http://localhost:8090/geoserver/beijing/wms/ows";
            var url = "http://localhost:8090/geoserver/taiwan/wms/ows";
            //var serverName = "beijing:footprints";
            var serverName = "taiwan:FWSL";
            queryUrl = url + "?service=WFS&version=1.0.0&request=GetFeature&typeName=" + serverName + "&outputFormat=application/json&srsName=EPSG:4326&filter=<Filter xmlns='http://www.opengis.net/ogc' xmlns:gml='http://www.opengis.net/gml'><Intersects><PropertyName>the_geom</PropertyName><gml:Point srsName='EPSG:3857'><gml:coordinates>" + point[0][0] + "," + point[0][1] + "</gml:coordinates></gml:Point></Intersects></Filter>";

            $.getJSON(queryUrl, function(data) {
                if (data.features.length === 0) {} else {
                    var dataArr = data.features[0].geometry.coordinates[0][0];
                    var newdata = ToWGS84(dataArr, true);
                    //addClapFeature(newdata);
                }
                //changeFeaturesForTable(data);
                showInfoWindow(event.position,data);
            });
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 将数据服务查询到的要素添加到场景中高亮显示，表示选中效果。
    function addClapFeature(feature) {
        viewer.entities.removeAll();
        var lonLatArr = getLonLatArray(feature);
        viewer.entities.add({
            id: 'identify-area',
            name: '单体化标识面',
            polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(lonLatArr),
                material: new Cesium.Color(1.0, 0.0, 0.0, 0.3),
            },
            clampToS3M: true // 贴在模型表面
        });
    }

    // 得到[经度,纬度,经度,纬度...]形式的数组，用于构造面。
    function getLonLatArray(points) {
        var point3D = [];
        points.forEach(function(point) {
            point3D.push(point[0]);
            point3D.push(point[1]);
        });
        return point3D;
    }
    function highLightGltf(pick){
        var primitives = viewer.scene.primitives;
        var length = primitives.length;
        for (var i = 0; i < length; ++i) {
            var p = primitives.get(i);
            p.color = new Cesium.Color(1,1,1,1);
        }

        //var pick = scene.pick(movement.position);
        if (Cesium.defined(pick) && Cesium.defined(pick.node) && pick.mesh){
            //console.log('node: ' + pick.node.name + '. mesh: ' + pick.mesh.name);
            pick.primitive.color =  Cesium.Color.YELLOW;
        }
    }
}